import Taro from '@tarojs/taro'
import { fetchToken } from './auth'

/**
 *
 * @param {统一请求方法} path
 * @param {*} method
 * @param {*} data
 */

export async function request(path, method = 'GET', data = {}) {
  // token
  let token = Taro.getStorageSync('Authorization')

  if (!token) {
    token = await fetchToken()
  }
  const header = {
    'client': 'miniProgram',
    'content-type': 'application/json'
  }
  token && (header.authorization = token)

  return new Promise((resolve, reject) => {
    const url = API_HOST + path

    return Taro.request({
      url, method, data, header
    }).then(async ({ statusCode, errMsg, data }) => {
      if (statusCode !== 200) {
        reject(data.msg.slice(0, data.msg.indexOf('   ERR')))
      }
      resolve(data)
    })
  })
}

export function get(url, data) {
  return request(url, 'GET', data)
}

export function post(url, data) {
  return request(url, 'POST', data)
}

export function put(url, data) {
  return request(url, 'PUT', data)
}

export function del(url, data) {
  return request(url, 'DELETE', data)
}
